package com.panopset.net.ftp;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.Socket;

/**
 *
 * FTP data socket.
 *
 * @author Karl Dinwiddie
 *
 */
public final class FTPDataSocket {

    /**
     * Socket wrapper.
     */
    private SocketWrapper sw;

    /**
     * Input stream.
     */
    private BufferedInputStream inputStream;

    /**
     * Output stream.
     */
    private BufferedOutputStream outputStream;

    /**
     * Constructor.
     *
     * @param host Host.
     * @param port Port.
     */
    FTPDataSocket(final String host, final int port) {
        sw = new SocketWrapper(host, port);
    }

    /**
     * Get the data socket.
     * @return Socket.
     * @throws IOException IO Exception.
     */
    public Socket getSocket() throws IOException {
        return sw.getSocket();
    }

    /**
     *
     * @return BufferedInputStream.
     * @throws IOException IO Exception.
     */
    BufferedInputStream getInputStream() throws IOException {
        if (inputStream == null) {
            inputStream = new BufferedInputStream(sw.getSocket()
                    .getInputStream());
        }
        return inputStream;
    }

    /**
     *
     * @return BufferedOutputStream.
     * @throws IOException IO Exception.
     */
    BufferedOutputStream getOutputStream() throws IOException {
        if (outputStream == null) {
            outputStream = new BufferedOutputStream(sw.getSocket()
                    .getOutputStream());
        }
        return outputStream;
    }

    /**
     * Close the data socket.
     * @throws IOException IO Exception.
     */
    public void close() throws IOException {
        if (inputStream != null) {
            inputStream.close();
        }
        if (outputStream != null) {
            outputStream.flush();
            outputStream.close();
        }
        inputStream = null;
        outputStream = null;
        sw.getSocket().close();
    }
}
